<template>
  <el-dialog v-model="form.visable" custom-class="module-form" title="提示" lock-scroll width="30%"
             append-to-body
  >
    <el-form class="module-form-body" :model="form.data" size="small">
      <el-form-item v-for="item in items" :key="item.prop" :label="item.label">
        <ModuleInput v-model="form.data[item.prop]" :type="item.type" :options="item.options" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="form.visable = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import ModuleInput from '@/components/FreeInput.vue'
import { defineComponent, reactive } from 'vue'
import { infoApi, saveApi, updateApi } from '@/api/component/searchTable'
import { useMessageBox, useMessage } from '@/hooks/useMessage'

export default defineComponent({
  name: 'FormModule',
  components: {
    ModuleInput,
  },
  props: {
    // 模型名称
    modelName: {
      type: String,
      required: true,
    },
    // 模型url
    modelUrl: {
      type: String,
      required: true,
    },
    // 表单渲染列表
    items: {
      type: Array,
      required: true,
    },
    // 表单类型 info | save | update
    task: {
      type: String,
      default: 'info',
    },
  },
  emits: ['submit'],
  setup(props, context) {
    const form = reactive({
      visable: false,
      data: {},
    })

    async function submitInfoEvent(primaryKey) {
      const {data} = await infoApi(`${props.modelUrl}/${primaryKey}`)
      return data
    }

    const submitSaveEvent = () => {
      saveApi(props.modelUrl, form.data).then(() => {
        useMessage.success('数据保存成功')
        form.visable = false
        context.emit('submit')
      })
    }
    const submitUpdateEvent = () => {
      updateApi(props.modelUrl, form.data).then(() => {
        useMessage.success('数据修改成功')
        form.visable = false
        context.emit('submit')
      })
    }

    // 打开弹框
    async function open(primaryKey: string | number) {
    console.log(primaryKey)
      if (primaryKey) {
        const data = await submitInfoEvent(primaryKey)
        if (data) {
          form.data = { ...data }
        }
      }
      form.visable = true
    }
    // 关闭弹框
    function close() {
      form.visable = false
    }

    const submit = () => {
      useMessageBox.warning('确定提交数据么?').then(() => {
        if (props.task === 'add') {
          submitSaveEvent()
        } else if (props.task === 'update') {
          submitUpdateEvent()
        }
      })
    }

    return {
      form,
      open,
      close,
      submit,
    }
  },
})
</script>

<style lang="scss" scoped>
.module-form {
  .module-form-body {
    height: 50vh;
    overflow-y: auto;
  }
  // > .el-dialog__body {
  //   height: 50vh;
  //   overflow-y: auto;
  // }
}
</style>
